<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="Java RMI 实战练习, 湮灭星空,博客,Python,后端">
    <meta name="description" content="Java RMI 实战练习
RMI代表远程方法调用。 这是一种允许位于在一个系统(JVM)中的对象访问/调用在另一个JVM上运行的对象的机制。
RMI用于构建分布式应用程序; 它提供Java程序之间的远程通信。 它在java.rmi包中提供">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>Java RMI 实战练习 | 湮灭星空</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<link rel="alternate" href="/atom.xml" title="湮灭星空" type="application/atom+xml">
</head>

<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper head-container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">湮灭星空</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友链</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">湮灭星空</div>
        <div class="logo-desc">
            
            天下寥寥，苍生涂涂，诸子百家，唯我纵横
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友链
		</a>
          
        </li>
        
        
    </ul>
</div>

        </div>

        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/23.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <div class="description center-align post-title">
                        Java RMI 实战练习
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/java/">
                                <span class="chip bg-color">java</span>
                            </a>
                        
                            <a href="/tags/jar/">
                                <span class="chip bg-color">jar</span>
                            </a>
                        
                            <a href="/tags/%E6%89%93%E5%8C%85/">
                                <span class="chip bg-color">打包</span>
                            </a>
                        
                            <a href="/tags/rmi/">
                                <span class="chip bg-color">rmi</span>
                            </a>
                        
                            <a href="/tags/stub/">
                                <span class="chip bg-color">stub</span>
                            </a>
                        
                            <a href="/tags/skeleton/">
                                <span class="chip bg-color">skeleton</span>
                            </a>
                        
                            <a href="/tags/server/">
                                <span class="chip bg-color">server</span>
                            </a>
                        
                            <a href="/tags/client/">
                                <span class="chip bg-color">client</span>
                            </a>
                        
                            <a href="/tags/%E8%BF%9C%E7%A8%8B%E6%8E%A5%E5%8F%A3/">
                                <span class="chip bg-color">远程接口</span>
                            </a>
                        
                            <a href="/tags/%E8%BF%9C%E7%A8%8B%E5%AF%B9%E8%B1%A1/">
                                <span class="chip bg-color">远程对象</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/Tech/" class="post-category">
                                Tech
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-01-17
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2020-01-17
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    2.5k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    9 分
                </div>
                
				
                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
            
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <h1 id="java-rmi-实战练习"><a class="header-anchor" href="#java-rmi-实战练习"></a>Java RMI 实战练习</h1>
<p>RMI代表远程方法调用。 这是一种允许位于在一个系统(JVM)中的对象访问/调用在另一个JVM上运行的对象的机制。<br>
RMI用于构建分布式应用程序; 它提供Java程序之间的远程通信。 它在java.rmi包中提供。</p>
<h2 id="rmi-应用程序的体系结构"><a class="header-anchor" href="#rmi-应用程序的体系结构"></a>RMI 应用程序的体系结构</h2>
<p>在RMI应用程序中，我们编写了两个程序，一个服务器程序(位于服务器上)和一个客户机程序(位于客户端上)。</p>
<ul>
<li>在服务器程序中，创建一个远程对象，该对象的引用可被客户端(使用注册表)使用。</li>
<li>客户端程序请求服务器上的远程对象，并尝试调用其方法。</li>
</ul>
<p>下图显示了RMI应用程序的体系结构：</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/ipic/2020-01-17-092207.jpg" alt="img"></p>
<p>下面我们来讨论这个架构的组件：</p>
<ul>
<li><strong>传输层(Transport Layer)</strong> - 此层连接客户端和服务器。它管理现有的连接，并设置新的连接。</li>
<li><strong>存根(Stub)</strong> - 存根是客户端上的远程对象的表示(代理)。 它位于客户端系统中; 它作为客户端程序的网关。</li>
<li><strong>骨架(Skeleton)</strong> - 它位于服务器端的对象。 存根与此骨架通信以将请求传递给远程对象。RRL(远程参考层) - 它是管理客户端对远程对象的引用的层。</li>
</ul>
<h2 id="rmi-应用程序的工作"><a class="header-anchor" href="#rmi-应用程序的工作"></a>RMI 应用程序的工作</h2>
<p>以下几点总结了RMI应用程序的工作原理 -</p>
<ul>
<li>当客户端调用远程对象时，它被存根最终传递给RRL。</li>
<li>当客户端RRL接收到请求时，它会调用对象<code>remoteRef</code>的一个名为<code>invoke()</code>的方法。 它将请求传递到服务器端的RRL。</li>
<li>服务器端的RRL将请求传递到服务器上的最后调用所需对象的<em>Skeleton</em>(服务器上的代理)。</li>
<li>结果一直传递给客户端。</li>
</ul>
<h2 id="rmi-注册"><a class="header-anchor" href="#rmi-注册"></a>RMI 注册</h2>
<p>RMI注册表是放置所有服务器对象的命名空间。 每次服务器创建一个对象时，它会使用<code>RMIregistry</code>(使用<code>bind（）</code>或<code>reBind()</code>方法)注册此对象。 这些使用叫作绑定名称(<code>bind name</code>)的唯一名称进行注册。<br>
要调用远程对象，客户端需要该对象的引用。客户端使用其绑定名称（使用<code>lookup()</code>方法）从注册表中获取对象。<br>
下图说明了整个过程：</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/ipic/2020-01-17-092453.jpg" alt="img"></p>
<h2 id="rmi-目标"><a class="header-anchor" href="#rmi-目标"></a>RMI 目标</h2>
<p>以下是RMI的目标：</p>
<ul>
<li>最小化应用程序的复杂性。</li>
<li>保护类型安全。</li>
<li>分布式垃圾收集。</li>
<li>最小化使用本地和远程对象之间的区别。</li>
</ul>
<h2 id="编写-rmi-应用程序"><a class="header-anchor" href="#编写-rmi-应用程序"></a>编写 RMI 应用程序</h2>
<h3 id="第一种编写方法"><a class="header-anchor" href="#第一种编写方法"></a>第一种编写方法</h3>
<p>要编写Java的RMI应用程序，必须遵循以下步骤：</p>
<ul>
<li>定义远程接口</li>
<li>开发实现类(远程对象)</li>
<li>开发服务器程序</li>
<li>开发客户端程序</li>
</ul>
<h4 id="定义远程接口"><a class="header-anchor" href="#定义远程接口"></a>定义远程接口</h4>
<p>远程接口提供特定远程对象的所有方法的描述。客户端可与此远程接口进行通信。</p>
<p>创建远程接口：</p>
<ul>
<li>创建一个扩展预定义接口的接口，该接口属于该包。</li>
<li>声明客户端在此界面中可以调用的所有业务方法。</li>
<li>由于在远程调用期间存在网络问题，因此可能会抛出一个名称为<code>RemoteException</code>的异常。</li>
</ul>
<p>以下是远程接口的示例。首先定义一个名为<code>Hello</code>的接口，此接口有一个名为<code>printMsg()</code>的方法</p>
<pre><code class="language-java">interface Hello extends Remote {
    // 远程服务接口

    void printMsg() throws RemoteException;
}
</code></pre>
<h4 id="开发实现类-remote-object"><a class="header-anchor" href="#开发实现类-remote-object"></a>开发实现类（Remote Object）</h4>
<p>我们需要实现在前面的步骤中创建的远程接口。可以单独写一个实现类，也可以直接使服务器程序实现这个接口。</p>
<p>开发一个实现类：</p>
<ul>
<li>实现上一步创建的接口。</li>
<li>提供远程接口的所有抽象方法的实现。</li>
</ul>
<p>以下是一个实现类。 在这里，我们创建了一个名为<code>ImplExample</code>的类，并实现了在上一步中创建的接口<code>Hello</code>，并提供了打印消息 - <code>printMsg()</code>方法的具体实现。</p>
<pre><code class="language-java">class ImplExample implements Hello {
    // 实现远程服务接口的类

    @Override
    public void printMsg() {
        System.out.println(&quot;This is an example RMI program.&quot;);
    }
}
</code></pre>
<h4 id="开发服务器程序"><a class="header-anchor" href="#开发服务器程序"></a>开发服务器程序</h4>
<p>RMI服务器程序应实现远程接口或扩展实现类。在这里，我们应该创建一个远程对象并将其绑定到<code>RMIregistry</code>。</p>
<p>开发服务器程序：</p>
<ul>
<li>从要调用远程对象的位置创建一个客户端类。</li>
<li>通过实例化实现类创建一个远程对象，如下所示。</li>
<li>使用属于包<code>java.rmi.server</code>中的<code>UnicastRemoteObject</code>类的<code>exportObject()</code>方法导出远程对象。</li>
<li><code>LocateRegistry.createRegistry(1099)</code> ，<code>1099</code> 为 <code>rmiregistry</code> 的默认端口（改了会报错，可能是什么地方用到了，这里改了其他地方也要改）， 创建 <code>rmiregistry</code></li>
<li>使用属于<code>java.rmi.registry</code>包中的<code>LocateRegistry</code>类的<code>getRegistry()</code>方法获取RMI注册表。</li>
<li>使用<code>Registry</code>类的bind()方法将创建的远程对象绑定到注册表。对于此方法，传递表示绑定名称和导出的对象的字符串作为参数。对于此方法，需要传递一个表示绑定名称的字符串值作为参数。这将返回远程对象。</li>
</ul>
<p>本程序可以直接运行启动服务器，以下是RMI服务器程序的示例，创建一名为：<strong>Server.java</strong>  的文件保存以下代码：</p>
<pre><code class="language-java">package com.yiibai;

import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

public class Server extends ImplExample {
    // 远程服务器

    public Server() {
    }

    public static void main(String[] args) {
        try {
            ImplExample obj = new ImplExample();
            Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);

            LocateRegistry.createRegistry(1099);    // 创建 rmiregistry
            Registry registry = LocateRegistry.getRegistry();
            registry.rebind(&quot;Hello&quot;, stub);

            System.out.println(&quot;Server ready&quot;);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}

class ImplExample implements Hello {
    // 实现远程服务接口的类

    @Override
    public void printMsg() {
        System.out.println(&quot;This is an example RMI program.&quot;);
    }
}

interface Hello extends Remote {
    // 远程服务接口

    void printMsg() throws RemoteException;
}
</code></pre>
<h4 id="开发客户端程序"><a class="header-anchor" href="#开发客户端程序"></a>开发客户端程序</h4>
<p>在这里我们编写一个客户端程序，获取远程对象并使用此对象调用所需的方法。</p>
<p>要开发客户端程序，请参考以下步骤 -</p>
<ul>
<li>从想要调用远程对象的地方创建一个客户端类。</li>
<li>使用属于<code>java.rmi.registry</code>包中的<code>LocateRegistry</code>类的<code>getRegistry()</code>方法获取RMI注册表。</li>
<li>使用属于<code>java.rmi.registry</code>包中的<code>Registry</code>类的<code>lookup()</code>方法从注册表获取对象。</li>
<li><code>lookup()</code>返回一个类型为<code>remote</code>的对象，将其转换为<code>Hello</code>类型。</li>
<li>最后使用获取的远程对象调用所需的方法。</li>
</ul>
<p>以下是RMI客户端程序的示例，创建一个名称为：<strong>Client.java</strong> 的文件：</p>
<pre><code class="language-java">package com.yiibai;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class Client {
    private Client() {
    }

    public static void main(String[] args) {
        try {
            Registry registry = LocateRegistry.getRegistry(null);
            Hello stub = (Hello) registry.lookup(&quot;Hello&quot;);
            stub.printMsg();
        } catch (RemoteException | NotBoundException e) {
            System.err.println(&quot;Client exception: &quot; + e.toString());
            e.printStackTrace();
        }
    }
}
</code></pre>
<h3 id="第二种编写方法"><a class="header-anchor" href="#第二种编写方法"></a>第二种编写方法</h3>
<p>要编写Java的RMI应用程序，必须遵循以下步骤：</p>
<ul>
<li>定义远程接口</li>
<li>开发服务器程序
<ul>
<li>直接使用服务器程序继承 <code>UnicastRemoteObject</code> 类</li>
<li>实现远程接口</li>
</ul>
</li>
<li>开发客户端程序</li>
</ul>
<h4 id="定义远程接口"><a class="header-anchor" href="#定义远程接口"></a>定义远程接口</h4>
<pre><code class="language-java">interface MyRemote extends Remote {
    // 远程服务接口
    String sayHello() throws RemoteException;
}
</code></pre>
<h4 id="开发服务器程序"><a class="header-anchor" href="#开发服务器程序"></a>开发服务器程序</h4>
<p>第一种写法：</p>
<ul>
<li>单独使用一个类实现远程接口，</li>
<li>在服务器程序中实例化实现远程接口的类（以下简称：实现类）</li>
<li>使用 <code>UnicastRemoteObject</code> 导出远程对象为 <code>stub</code></li>
<li>使用默认端口 <code>1099</code> 创建 <code>RMI registry</code></li>
<li>再将 <code>stub</code> 注册到 <code>RMI registry</code> 供客户端调用</li>
</ul>
<p>第二种写法：</p>
<ul>
<li>不单独定义实现类，直接将服务器程序当做远程接口的实现类
<ul>
<li>前提是需要定义无参数的构造函数，因为父类的构造函数声明了异常，表示构造函数将会调用有风险的代码</li>
<li>实现远程接口的所有方法</li>
</ul>
</li>
<li>实例化服务器程序（本身就是远程对象）</li>
<li>使用默认端口 <code>1099</code> 创建 <code>RMI registry</code></li>
<li>再使用静态的 <code>Naming.rebind</code> 注册服务，供客户端调用</li>
</ul>
<pre><code class="language-java">package chap18;

import java.net.MalformedURLException;
import java.rmi.*;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.*;

public class MyRemoteServer extends UnicastRemoteObject implements MyRemote {
    // 远程服务器
    // 创建远程对象最简单的方式就是继承 UnicastRemoteObject
    // 实现一个远程接口（实现接口的所有方法）

    @Override
    public String sayHello() {
        // 接口的方法
        return &quot;Server say hello!&quot;;
    }

    private MyRemoteServer() throws RemoteException {
        // 父类的构造函数声明了异常，所以这里必须写出狗杂函数
        // 因为它代表构造函数会调用有风险的代码
    }


    public static void main(String[] args) {
        try {
            MyRemote service = new MyRemoteServer();    // 创建远程对象

            LocateRegistry.createRegistry(1099);    // 创建 rmiregistry

            Naming.rebind(&quot;RemoteHello&quot;, service);  // 使用静态的 Naming.rebind 注册服务
            System.out.println(&quot;Server is ready!&quot;);
        } catch (RemoteException | MalformedURLException e) {
            e.printStackTrace();
        }
    }
}

interface MyRemote extends Remote {
    // 远程服务接口
    String sayHello() throws RemoteException;
}
</code></pre>
<h4 id="开发客户端程序"><a class="header-anchor" href="#开发客户端程序"></a>开发客户端程序</h4>
<p>客户端程序很简单：</p>
<ul>
<li>使用 <code>Naming.lookup(&quot;RemoteHello&quot;)</code> 查询服务，获得服务端返回的远程对象</li>
<li>直接使用该远程对象调用服务端的方法</li>
</ul>
<pre><code class="language-java">package chap18;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;

public class MyRemoteClient {
    public static void main(String[] args) {
        new MyRemoteClient().go();
    }

    public void go() {
        try {
            MyRemote service = (MyRemote) Naming.lookup(&quot;RemoteHello&quot;);
            String s = service.sayHello();  // 调用服务端的 sayHello 方法，获取服务端返回的字符串
            System.out.println(s);
        } catch (RemoteException | NotBoundException | MalformedURLException e) {
            e.printStackTrace();
        }
    }
}

</code></pre>
<h3 id="编译应用程序"><a class="header-anchor" href="#编译应用程序"></a>编译应用程序</h3>
<p>编译应用程序：</p>
<ul>
<li>编译远程接口</li>
<li>编译实现类</li>
<li>编译服务器程序</li>
<li>编译客户端程序</li>
</ul>
<p>或者直接编译所以 java 文件：</p>
<pre><code class="language-shell">javac *.java
</code></pre>
<h3 id="执行应用程序"><a class="header-anchor" href="#执行应用程序"></a>执行应用程序</h3>
<p>执行 class 文件：</p>
<pre><code class="language-shell">java Server
java Client
</code></pre>
<p>或者</p>
<p>执行 java 文件</p>
<pre><code class="language-shell">java Server.java
java Client.java
</code></pre>
<p>当然在 IDEA 里面执行更方便。</p>
<h2 id="延伸"><a class="header-anchor" href="#延伸"></a>延伸</h2>
<h3 id="使用终端启动-rmiregistry-时-server无法启动"><a class="header-anchor" href="#使用终端启动-rmiregistry-时-server无法启动"></a>使用终端启动 <code>rmiregistry</code> 时 <code>Server</code>无法启动</h3>
<p>两种方法的代码中都是使用</p>
<pre><code class="language-java">LocateRegistry.createRegistry(1099);
</code></pre>
<p>创建 <code>rmiregistry</code>，<code>Head First Java</code> 书中推荐的是在终端另外启动 <code>rmiregistry</code>，实际测试使用下面命令确实启动了 <code>rmiregistry</code>，但<code>Server.java</code>运行总是报错。</p>
<pre><code class="language-shell">rmiregistry 1099 &amp;
</code></pre>
<p>报错如下：</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/ipic/2020-01-17-100700.png" alt="image-20200117180659939"></p>

<div id="gitalk-container"></div>
<script src="https://cdn.bootcss.com/blueimp-md5/2.12.0/js/md5.min.js"></script><link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css"><script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>

		<script>
		var gitalkConfig = {"clientID":"9eb5bc3ac1e1ff3ddac0","clientSecret":"4b7ae28042282281295075c2bf0c97ff1791cfeb","repo":"HexoBlogComments","owner":"Annihilater","admin":["Annihilater"],"distractionFreeMode":false};
	    gitalkConfig.id = md5(location.pathname);
		var gitalk = new Gitalk(gitalkConfig);
	    gitalk.render("gitalk-container");
	    </script>
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://www.klause.cn" rel="external nofollow noreferrer">湮灭星空</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://www.klause.cn/2020/01/17/java/java-rmi-shi-zhan-lian-xi/">https://www.klause.cn/2020/01/17/java/java-rmi-shi-zhan-lian-xi/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="https://www.klause.cn" target="_blank">湮灭星空</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/java/">
                                    <span class="chip bg-color">java</span>
                                </a>
                            
                                <a href="/tags/jar/">
                                    <span class="chip bg-color">jar</span>
                                </a>
                            
                                <a href="/tags/%E6%89%93%E5%8C%85/">
                                    <span class="chip bg-color">打包</span>
                                </a>
                            
                                <a href="/tags/rmi/">
                                    <span class="chip bg-color">rmi</span>
                                </a>
                            
                                <a href="/tags/stub/">
                                    <span class="chip bg-color">stub</span>
                                </a>
                            
                                <a href="/tags/skeleton/">
                                    <span class="chip bg-color">skeleton</span>
                                </a>
                            
                                <a href="/tags/server/">
                                    <span class="chip bg-color">server</span>
                                </a>
                            
                                <a href="/tags/client/">
                                    <span class="chip bg-color">client</span>
                                </a>
                            
                                <a href="/tags/%E8%BF%9C%E7%A8%8B%E6%8E%A5%E5%8F%A3/">
                                    <span class="chip bg-color">远程接口</span>
                                </a>
                            
                                <a href="/tags/%E8%BF%9C%E7%A8%8B%E5%AF%B9%E8%B1%A1/">
                                    <span class="chip bg-color">远程对象</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
        </div>
    </div>

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2020/01/21/mac/mac-xia-wu-fa-tui-chu-ying-pan-zen-me-ban/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/8.jpg" class="responsive-img" alt="Mac 下无法退出硬盘怎么办？">
                        
                        <span class="card-title">Mac 下无法退出硬盘怎么办？</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            Mac 下无法退出硬盘怎么办？
Mac 下推出硬盘的时候报硬盘正在被程序使用无法推出的时候怎么办？
使用 lsof 命令：
lsof 硬盘的绝对路径

可以显示出，有哪些进程正在使用硬盘。效果如下：


本人本机移动硬盘的路径是 /Volu
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-01-21
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Tech/" class="post-category">
                                    Tech
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Mac/">
                        <span class="chip bg-color">Mac</span>
                    </a>
                    
                    <a href="/tags/%E7%A7%BB%E5%8A%A8%E7%A1%AC%E7%9B%98/">
                        <span class="chip bg-color">移动硬盘</span>
                    </a>
                    
                    <a href="/tags/kill/">
                        <span class="chip bg-color">kill</span>
                    </a>
                    
                    <a href="/tags/lsof/">
                        <span class="chip bg-color">lsof</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2020/01/16/java/java-da-bao-jar/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/19.jpg" class="responsive-img" alt="Java 打包 JAR">
                        
                        <span class="card-title">Java 打包 JAR</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            Java 打包 JAR
项目
先创建好 Java 项目 MyProject，目录结构如下：


source 文件夹：java 源码目录
classes 文件夹：编译生成的文件所存放的目录
test.java 文件内容如下

package
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-01-16
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Tech/" class="post-category">
                                    Tech
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/java/">
                        <span class="chip bg-color">java</span>
                    </a>
                    
                    <a href="/tags/jar/">
                        <span class="chip bg-color">jar</span>
                    </a>
                    
                    <a href="/tags/%E6%89%93%E5%8C%85/">
                        <span class="chip bg-color">打包</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>

    
<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>

    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            // headingsOffset: -205,
            headingSelector: 'h2, h3, h4, h5, h6'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4, h5, h6').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>



    <footer class="page-footer bg-color">
    <div class="container row center-align">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">年份</span>
            <a href="https://www.klause.cn" target="_blank">湮灭星空</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">199.2k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    window.setTimeout("siteTime()", 1000);
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2019";
                    var startMonth = "6";
                    var startDate = "28";
                    var startHour = "0";
                    var startMinute = "0";
                    var startSecond = "0";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
            <span id="icp"><img src="/medias/icp.png" style="vertical-align: text-bottom;" />
                <a href="http://www.beian.miit.gov.cn" target="_blank">皖ICP备18005729号-1</a>
            </span>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/Annihilater" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:yanmiexingkong@gmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>





    <a href="https://twitter.com/" class="tooltipped" target="_blank" data-tooltip="关注我的Twitter: https://twitter.com/" data-position="top" data-delay="50">
        <i class="fab fa-twitter"></i>
    </a>







    <a href="https://www.zhihu.com/" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>

    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Global site tag (gtag.js) - Google Analytics -->


    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    
    
    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
